<!-- 系统成本-子系统对应的数据展示 -->
<template>
  <div class="system-efficiency-wrap">
    <div v-loading="loading" class="content-wrap">
      <px-row :gutter="16">
        <px-col :span="9">
          <div class="black black-4">
            <div class="data-wrap">
              <div class="data-left">
                <img class="left-img" src="@/assets/images/energy/lightOverView/ng_cost.png" />
              </div>
              <div class="data-right">
                <div class="item">
                  <div class="item-top-wrap">
                    <div class="text">{{ systemDataObj?.outputName }}</div>
                  </div>
                  <div class="num-wrap">
                    <px-tooltip v-if="outPutShow" effect="dark" :content="String(systemDataObj?.output)" placement="top">
                      <div ref="outPutRef" class="num">{{ systemDataObj?.output }}</div>
                    </px-tooltip>
                    <div v-else ref="outPutRef" class="num">{{ systemDataObj?.output || "-" }}</div>
                    <div class="unit">{{ systemDataObj?.outputUnit }}</div>
                  </div>
                </div>
                <div class="item">
                  <div class="item-top-wrap">
                    <div class="text">同期</div>
                    <div :class="[systemDataObj?.outputYoy > 0 ? 'up' : 'down', systemDataObj?.outputYoy === '-' ? 'foo' : '']">
                      {{ systemDataObj?.outputYoyText }}
                    </div>
                  </div>
                  <div class="num-wrap">
                    <px-tooltip v-if="outputYoyValueShow" effect="dark" :content="String(systemDataObj?.outputYoyValue)" placement="top">
                      <div ref="outputYoyValueRef" class="num">{{ systemDataObj?.outputYoyValue }}</div>
                    </px-tooltip>
                    <div v-else ref="outputYoyValueRef" class="num">{{ systemDataObj?.outputYoyValue }}</div>
                    <div class="unit">{{ systemDataObj?.outputUnit }}</div>
                  </div>
                </div>
                <div class="item">
                  <div class="item-top-wrap">
                    <div class="text">上期</div>
                    <div :class="[systemDataObj?.outputMom > 0 ? 'up' : 'down', systemDataObj?.outputMom === '-' ? 'foo' : '']">
                      {{ systemDataObj?.outputMomText }}
                    </div>
                  </div>
                  <div class="num-wrap">
                    <px-tooltip v-if="outputMomValueShow" effect="dark" :content="String(systemDataObj?.outputMomValue)" placement="top">
                      <div ref="outputMomValueRef" class="num">{{ systemDataObj?.outputMomValue }}</div>
                    </px-tooltip>
                    <div v-else ref="outputMomValueRef" class="num">{{ systemDataObj?.outputMomValue }}</div>
                    <div class="unit">{{ systemDataObj?.outputUnit }}</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="title-wrap">
              <modelTitle :title="'总产出与能耗'" />
              <btnImageAndData
                v-has="'ALL_ENERGY_COST_SYSTEM_DOWNLOAD'"
                class="top"
                :exportImage="Boolean(false)"
                @exportChange="val => handlerExport(val, 'table', 'summary', '')"
              />
            </div>
            <!-- <px-button v-has="'ALL_ENERGY_COST_SYSTEM_DOWNLOAD'" class="btn-export top" @click="handleExport('summary')">导出</px-button> -->
            <px-table
              v-if="systemDataObj.summaryTable?.length"
              max-height="184"
              class="table-wrap"
              :data="systemDataObj.summaryTable"
              size="small"
              border
              stripe
              show-overflow-tooltip
            >
              <template v-for="item in tableHeader" :key="item.prop">
                <px-table-column :prop="item.prop" :label="item.label">
                  <!-- 同比和环比颜色处理 -->
                  <template v-if="['yoyText', 'momText'].includes(item.prop)" #default="scope">
                    <span :class="[scope.row[item.flag] > 0 ? 'up' : 'down', scope.row[item.flag] === '-' ? 'foo' : '']">{{
                      scope.row[item.prop] || "-"
                    }}</span>
                  </template>
                  <template v-else #default="scope">
                    {{ scope.row[item.prop] || "-" }}
                  </template>
                </px-table-column>
              </template>
            </px-table>
            <px-empty v-else :image-size="50" />
          </div>
        </px-col>
        <px-col :span="15">
          <div class="black black-8">
            <modelTitle :title="'总能耗趋势图'" />
            <btnImageAndData
              v-has="'ALL_ENERGY_COST_SYSTEM_DOWNLOAD'"
              class="btn-export"
              :exportData="Boolean(false)"
              @exportChange="val => handlerExport(val, '', '', 'systemSummaryLineRef')"
            />
            <div v-if="systemDataObj?.summaryTrend" ref="systemSummaryLineRef" style="width: 100%" class="chart-wrap" />
            <px-empty v-else :image-size="120" />
          </div>
        </px-col>
      </px-row>
      <px-row :gutter="16" class="mg-top-16">
        <px-col :span="9">
          <div class="black black-4">
            <modelTitle :title="'单位产量能耗'" />
            <btnImageAndData
              v-has="'ALL_ENERGY_COST_SYSTEM_DOWNLOAD'"
              class="btn-export"
              :exportImage="Boolean(false)"
              @exportChange="val => handlerExport(val, 'table', 'unit', '')"
            />
            <!-- <px-button v-has="'ALL_ENERGY_COST_SYSTEM_DOWNLOAD'" class="btn-export" @click="handleExport('unit')">导出</px-button> -->
            <px-table
              v-if="systemDataObj.unitTable?.length"
              max-height="184"
              class="table-wrap"
              :data="systemDataObj.unitTable"
              size="small"
              border
              stripe
              show-overflow-tooltip
            >
              <template v-for="item in tableHeader" :key="item.prop">
                <px-table-column :prop="item.prop" :label="item.label">
                  <!-- 同比和环比颜色处理 -->
                  <template v-if="['yoyText', 'momText'].includes(item.prop)" #default="scope">
                    <span :class="[scope.row[item.flag] > 0 ? 'up' : 'down', scope.row[item.flag] === '-' ? 'foo' : '']">{{
                      scope.row[item.prop] ?? "-"
                    }}</span>
                  </template>
                  <template v-else #default="scope">
                    {{ scope.row[item.prop] ?? "-" }}
                  </template>
                </px-table-column>
              </template>
            </px-table>
            <px-empty v-else :image-size="120" />
          </div>
        </px-col>
        <px-col :span="15">
          <div class="black black-8">
            <modelTitle :title="'单耗趋势图'" />
            <btnImageAndData
              v-has="'ALL_ENERGY_COST_SYSTEM_DOWNLOAD'"
              class="btn-export"
              :exportData="Boolean(false)"
              @exportChange="val => handlerExport(val, '', '', 'systemUnitLineRef')"
            />
            <div v-if="systemDataObj?.unitTrend" ref="systemUnitLineRef" style="width: 100%" class="chart-wrap" />
            <px-empty v-else :image-size="120" />
          </div>
        </px-col>
      </px-row>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, toRefs, onMounted, onUpdated, computed, watch, getCurrentInstance } from "vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import btnImageAndData from "@/views/common/energy/components/btnImageAndData/index.vue";
import * as echarts from "echarts";
import { getViewConsumeSystemApi } from "@/api/energy/energyCost";

const { proxy } = getCurrentInstance();

const props = defineProps({
  queryParams: {
    type: Object,
    default: () => {}
  }
});

const state = reactive({
  tableHeader: [
    {
      label: "消耗能源",
      prop: "name",
      flag: "name",
      align: "left"
    },
    {
      label: "耗能总费用",
      prop: "sum",
      flag: "sum",
      align: "left"
    },
    {
      label: "同比",
      prop: "yoyText",
      flag: "yoy",
      align: "left"
    },
    {
      label: "环比",
      prop: "momText",
      flag: "mom",
      align: "left"
    },
    {
      label: "占比",
      prop: "ratioText",
      flag: "ratio",
      align: "left"
    }
  ],
  loading: false,
  systemDataObj: {
    dimension: "",
    startDate: "",
    endDate: "",
    systemName: "", //子系统名称
    outputName: "", //	总产出名称
    outputUnit: "", //总产出单位
    output: "", //总产出量
    outputYoyValue: "", //总产出量 同期
    outputYoy: "", //	总产出量 同比
    outputMomValue: "", //总产出量 上期
    outputMom: "", //总产出量 环比
    summaryTable: [], //总产出与能耗表格
    unitTable: [], //单位产量能耗表格
    summaryTrend: {
      xaxis: [],
      yaxis: []
    }, // 总产出与能耗年度配额消耗趋势
    unitTrend: {
      xaxis: [],
      yaxis: []
    } // 单位产量能耗年度配额消耗趋势
  },
  dataObj: {}
});
const outPutRef = ref();
const outPutShow = ref(false);
const outputYoyValueRef = ref();
const outputYoyValueShow = ref(false);
const outputMomValueRef = ref();
const outputMomValueShow = ref(false);
const systemSummaryLineRef = ref();
const systemUnitLineRef = ref();
const queryParams = computed(() => props.queryParams);
const { tableHeader, loading, systemDataObj } = toRefs(state);
let chartObj = {};
onMounted(() => {
  // getSystemData();
});
onUpdated(() => {
  checkOverflow();
});

// 检查文本是否溢出
const checkOverflow = () => {
  if (outPutRef.value) {
    outPutShow.value = outPutRef.value.scrollWidth > outPutRef.value.clientWidth;
  }
  if (outputYoyValueRef.value) {
    outputYoyValueShow.value = outputYoyValueRef.value.scrollWidth > outputYoyValueRef.value.clientWidth;
  }
  if (outputMomValueRef.value) {
    outputMomValueShow.value = outputMomValueRef.value.scrollWidth > outputMomValueRef.value.clientWidth;
  }
};
watch(
  () => props.queryParams,
  val => {
    if (val.sysId) {
      getSystemData();
    }
  },
  { deep: true }
);
// 获取参数
const getParams = () => {
  let obj = {
    Daily: "D",
    Monthly: "M",
    Yearly: "Y"
  };
  let { startDate, endDate, sysId } = queryParams.value;
  let dimension = obj[queryParams.value?.dimension] || "";

  return {
    startDate,
    endDate,
    dimension,
    sysId
  };
};

// 系统成本
const getSystemData = async () => {
  try {
    state.loading = true;
    const { startDate, endDate, dimension, sysId } = getParams();
    const params = {
      factoryId: "",
      facCode: "",
      dimension: dimension,
      startDate: startDate,
      endDate: endDate,
      sysId: sysId,
      unit: ""
    };
    const res = await getViewConsumeSystemApi(params);
    state.dataObj = JSON.parse(JSON.stringify(res));
    let summarySum = res.summaryTable[res.summaryTable.length - 1];
    res?.summaryTable?.forEach((i, index) => {
      if (i.qty === 0) {
        i.account = "-";
      } else {
        i.account = ((i.qty / summarySum.qty) * 100).toFixed(2) + "%";
      }

      i.sum = i.qty + i.unit;
      if (i.yoy !== null) {
        i.yoyText = i.yoy > 0 ? "+" + i.yoy + "%" : i.yoy + "%";
      } else {
        i.yoyText = "-";
        i.yoy = "-";
      }
      if (i.mom !== null) {
        i.momText = i.mom > 0 ? "+" + i.mom + "%" : i.mom + "%";
      } else {
        i.momText = "-";
        i.mom = "-";
      }
      if (i.ratio !== null) {
        i.ratioText = i.ratio + "%";
      } else {
        i.ratioText = "-";
        i.ratio = "-";
      }
    });
    let unitSum = res.unitTable[res.unitTable.length - 1];
    res?.unitTable?.forEach(i => {
      if (i.qty === 0) {
        i.account = "-";
      } else {
        i.account = ((i.qty / unitSum.qty) * 100).toFixed(2) + "%";
      }

      i.sum = i.qty + i.unit;
      if (i.yoy !== null) {
        i.yoyText = i.yoy > 0 ? "+" + i.yoy + "%" : i.yoy + "%";
      } else {
        i.yoyText = "-";
        i.yoy = "-";
      }
      if (i.mom !== null) {
        i.momText = i.mom > 0 ? "+" + i.mom + "%" : i.mom + "%";
      } else {
        i.momText = "-";
        i.mom = "-";
      }
      if (i.ratio !== null) {
        i.ratioText = i.ratio + "%";
      } else {
        i.ratioText = "-";
        i.ratio = "-";
      }
    });
    res.output = res?.output !== null ? String(res?.output) : "-";
    if (res?.outputMom !== null) {
      res.outputMomText = res?.outputMom > 0 ? "+" + res?.outputMom + "%" : res?.outputMom + "%";
    } else {
      res.outputMomText = "-";
      res.outputMom = "-";
    }
    res.outputMomValue = res?.outputMomValue !== null ? String(res?.outputMomValue) : "-";
    if (res?.outputYoy !== null) {
      res.outputYoyText = res?.outputYoy > 0 ? "+" + res?.outputYoy + "%" : res?.outputYoy + "%";
    } else {
      res.outputYoyText = "-";
      res.outputYoy = "-";
    }
    res.outputYoyValue = res?.outputYoyValue !== null ? String(res?.outputYoyValue) : "-";
    checkOverflow();
    state.systemDataObj = res;
    res?.summaryTrend ? drawBarLineChart(systemSummaryLineRef.value, res?.summaryTrend, "systemSummaryLineRef") : "";
    res?.unitTrend ? drawBarLineChart(systemUnitLineRef.value, res?.unitTrend, "systemUnitLineRef") : "";
  } catch (error) {
  } finally {
    state.loading = false;
  }
};
// 能效计量-折线图
const drawBarLineChart = (dom, obj, args) => {
  const colors = ["#FD7C7C", "#3B82F6", "#13C2C2", "#FFC53D", "#FD7C7C", "#3B82F6", "#13C2C2", "#FFC53D"];
  let yAxisAry = [];
  let seenUnits = new Map(); // 用来进行去重
  let seriesData = [];
  obj?.yaxis?.forEach((i, idx) => {
    if (i.name === "产出量") {
      seriesData.push({
        name: i.name,
        type: "line",
        yAxisIndex: idx,
        data: i.value,
        unit: i.unit,
        tooltip: {
          valueFormatter: function (value) {
            if (value === null || value === undefined) {
              value = "-";
            }
            return value + " " + i.unit;
          }
        }
      });
    } else {
      seriesData.push({
        name: i.name,
        type: "bar",
        yAxisIndex: idx,
        data: i.value,
        unit: i.unit,
        tooltip: {
          valueFormatter: function (value) {
            if (value === null || value === undefined) {
              value = "-";
            }
            return value + " " + i.unit;
          }
        }
      });
    }
    if (!seenUnits.has(i.unit)) {
      seenUnits.set(i.unit, true);
    }
  });
  [...seenUnits]?.forEach(([key, value], idx) => {
    yAxisAry.push({
      type: "value",
      name: key,
      alignTicks: true,
      axisLabel: {
        formatter: function (value) {
          if (value >= 1000000000) {
            return (value / 1000000000).toFixed(1) + "B"; // 十亿
          } else if (value >= 1000000) {
            return (value / 1000000).toFixed(1) + "M"; // 百万
          } else if (value >= 1000) {
            return (value / 1000).toFixed(1) + "K"; // 千
          }
          return value; // 原始值
        }
      },
      position: idx === 0 ? "left" : "right",
      offset: idx === 0 ? 0 : (idx - 1) * 60,
      axisLine: {
        show: true,
        lineStyle: {
          color: colors[idx]
        }
      }
    });
  });
  seriesData?.forEach(i => {
    const idx = yAxisAry?.findIndex(j => j.name === i.unit);
    i.yAxisIndex = idx;
  });

  let options = {
    color: colors,
    tooltip: {
      trigger: "axis"
    },
    grid: {
      right: `${yAxisAry.length > 1 ? (yAxisAry.length - 1) * 5 : 10}%`,
      bottom: "10%"
    },
    // toolbox: {
    //   show: true,
    //   feature: {
    //     saveAsImage: {
    //       title: "点击保存为图片"
    //     }
    //   }
    // },
    legend: {},
    xAxis: [
      {
        type: "category",
        axisTick: {
          alignWithLabel: true
        },
        data: obj?.xaxis || []
      }
    ],
    yAxis: yAxisAry,
    series: seriesData
  };
  let myChart = echarts.init(dom);
  chartObj[args] = myChart;
  myChart.clear();
  myChart.setOption(options);
};
// 导出
const handleExport = val => {
  let params = state.dataObj;
  params.type = "table";
  params.summaryUnit = val;
  let obj = {
    summary: "总产出与能耗",
    unit: "单位产量能耗"
  };
  let name = `系统成本-${obj[val]}.xlsx`;
  proxy.download("post", "/energy/energyCost/exportConsumeSystem", params, name);
};
const handlerExport = (val1, val2, val3, val4) => {
  console.log(val1, val2, val3, val4);
  if (val1 === "data") {
    if (val2 === "table") {
      let params = state.dataObj;
      params.type = "table";
      params.summaryUnit = val3;
      let obj = {
        summary: "总产出与能耗",
        unit: "单位产量能耗"
      };
      let name = `系统成本-${obj[val3]}.xlsx`;
      proxy.download("post", "/energy/energyCost/exportConsumeSystem", params, name);
    }
  } else {
    let myChart = chartObj[val4];
    if (!myChart) return;
    // 获取Base64图片数据
    const imgUrl = myChart.getDataURL({
      type: "png",
      pixelRatio: 2,
      backgroundColor: "#fff"
    });
    // 创建并触发下载链接
    const link = document.createElement("a");
    link.href = imgUrl;
    link.download = "chart.png";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
};
</script>
<style lang="scss" scoped>
.system-efficiency-wrap {
  flex: 1;
}

.content-wrap {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.px-row {
  flex: 1;
}

.black {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;
}

.data-wrap {
  display: flex;
  margin-bottom: 10px;
  color: #000;

  .data-left {
    display: flex;
    min-width: 48px;
    margin-right: 10px;

    .left-img {
      width: 48px;
      height: 48px;
      margin-right: 12px;
    }
  }

  .unit {
    margin: 0 2px;
    font-size: 14px;
  }

  .data-right {
    display: flex;
    flex: 1;
    flex-wrap: wrap;
    align-items: center;

    .item {
      display: flex;
      flex: 1;
      flex-direction: column;
      justify-content: center;
      margin-right: 10px;

      .item-top-wrap {
        display: flex;
        align-items: baseline;
      }

      .text {
        margin-right: 10px;
        font-size: 12px;
        font-weight: 400;
      }

      .num-wrap {
        display: flex;
        align-items: baseline;
      }

      .num {
        max-width: 100px;
        overflow: hidden;
        font-size: 20px;
        font-weight: 500;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .down {
        font-size: 14px;
        color: #34d399;
      }

      .foo {
        color: rgb(0 0 0 / 80%);
      }

      .up {
        font-size: 14px;
        color: #f00;
      }
    }
  }
}

.title-wrap {
  position: relative;
}

.table-wrap {
  flex: 1;
  margin-top: 16px;

  .down {
    color: #34d399;
  }

  .foo {
    color: rgb(0 0 0 / 80%);
  }

  .up {
    color: #f00;
  }
}

.mg-top-16 {
  margin-top: 16px;
}

.chart-wrap {
  flex: 1;
}

.btn-export {
  position: absolute;
  top: 16px;
  right: 24px;
}

.top {
  position: absolute;
  top: 0;
  right: 0;
}
</style>
